package com.example.auv_660;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.auv_660.network.tcp.HFTCPBuild;
import com.example.auv_660.network.udp.HFUDPBuild;
import com.example.auv_660.util.Constants;
import com.example.auv_660.util.MsgType;
import com.example.auv_660.util.Tools;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ImageView heart_view;           // 心跳
    private ImageView chaoshen;             // 超深警示
    private ImageView chaoshi;              // 超时警示
    private ImageView shache;               // 制动警示

    private List<TextView> arrayList;       // 信息列表

    private TextView distance;              // 距离
    private TextView calculateYaw;          // 角度

    private LinearLayout linearLayoutView;  //信息列表边框

    private static MainActivity instance;
    public static MainActivity getInstance()
    {
        return instance;
    }

    private WindowManager.LayoutParams lp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 保持屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);

        heart_view = findViewById(R.id.heartview);
        chaoshen = findViewById(R.id.chaoshen);
        chaoshi = findViewById(R.id.chaoshi);
        shache = findViewById(R.id.shache);

        linearLayoutView = findViewById(R.id.table);

        buildTable();                       // 创建信息列表并赋初值

        distance = findViewById(R.id.distance);
        calculateYaw = findViewById(R.id.calculateYaw);

        instance = this;
        HFUDPBuild.INSTANCE.getHFUdpClient().udpWorker();           // 开启UDP连接
        HFTCPBuild.INSTANCE.getHFTcpServer().tcpWorker();           // 开启TCP连接
    }

    private void buildTable()
    {
        arrayList = new ArrayList<>();
        TextView reitt = new TextView(this);
        reitt.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 2));
        reitt.setBackgroundColor(Color.BLACK);
        linearLayoutView.addView(reitt);
        for (int i = 0; i < 21; i++)
        {
            LinearLayout linearLayout = new LinearLayout(this);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            for (int j = 0; j < 3; j++)
            {
                TextView textView = new TextView(this);
                arrayList.add(textView);
                if (j % 3 == 2)
                {
                    textView.setLayoutParams(new LinearLayout.LayoutParams(5, LinearLayout.LayoutParams.WRAP_CONTENT, 2));
                }
                else
                {
                    textView.setLayoutParams(new LinearLayout.LayoutParams(5, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
                }
                textView.setGravity(Gravity.CENTER);
                linearLayout.addView(textView);
                TextView reit = new TextView(this);
                reit.setLayoutParams(new LinearLayout.LayoutParams(2, LinearLayout.LayoutParams.MATCH_PARENT));
                reit.setBackgroundColor(Color.BLACK);
                linearLayout.addView(reit);
            }

            TextView reit = new TextView(this);
            reit.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 2));
            reit.setBackgroundColor(Color.BLACK);
            linearLayoutView.addView(reit);
            linearLayoutView.addView(linearLayout, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        }
        updateTable();
    }

    private void updateTable()
    {
        arrayList.get(0).setText("序号");
        arrayList.get(1).setText("参数");
        arrayList.get(2).setText("参数值");
        for (int i = 0; i < 3; i++)
        {
            arrayList.get(i).setTextSize(26);
            arrayList.get(i).setBackgroundColor(Color.parseColor("#CCCCCC"));
        }

        arrayList.get(3).setText("1");
        arrayList.get(4).setText("GPS经度");
        arrayList.get(6).setText("2");
        arrayList.get(7).setText("GPS纬度");
        arrayList.get(9).setText("3");
        arrayList.get(10).setText("GPS高度");
        arrayList.get(12).setText("4");
        arrayList.get(13).setText("GPS时间");
        arrayList.get(15).setText("5");
        arrayList.get(16).setText("GPS精度");
        for (int i = 3; i < 18; i++)
        {
            arrayList.get(i).setTextSize(17);
            arrayList.get(i).setBackgroundColor(Color.parseColor("#FFCC99"));
        }

        arrayList.get(18).setText("6");
        arrayList.get(19).setText("航向角");
        arrayList.get(21).setText("7");
        arrayList.get(22).setText("俯仰角");
        arrayList.get(24).setText("8");
        arrayList.get(25).setText("横滚角");
        for (int i = 18; i < 27; i++)
        {
            arrayList.get(i).setTextSize(17);
            arrayList.get(i).setBackgroundColor(Color.parseColor("#FFFFCC"));
        }

        arrayList.get(27).setText("9");
        arrayList.get(28).setText("服务器");
        arrayList.get(30).setText("10");
        arrayList.get(31).setText("操控端");
        for (int i = 27; i < 33; i++)
        {
            arrayList.get(i).setTextSize(17);
            arrayList.get(i).setBackgroundColor(Color.parseColor("#FFFFCC"));
        }

        arrayList.get(33).setText("11");
        arrayList.get(34).setText("AUVID");
        arrayList.get(35).setText(Constants.PHONEIMEI);
        arrayList.get(36).setText("12");
        arrayList.get(37).setText("动力IP");
        arrayList.get(39).setText("13");
        arrayList.get(40).setText("动力反馈");
        arrayList.get(42).setText("14");
        arrayList.get(43).setText("深度IP");
        arrayList.get(45).setText("15");
        arrayList.get(46).setText("深度反馈");
        arrayList.get(48).setText("16");
        arrayList.get(49).setText("电量IP");
        arrayList.get(51).setText("17");
        arrayList.get(52).setText("电量反馈");
        for (int i = 33; i < 54; i++)
        {
            arrayList.get(i).setTextSize(17);
            arrayList.get(i).setBackgroundColor(Color.parseColor("#99CCCC"));
        }
    }

    // 从HFUDPBuild接口反馈显示
    private Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case MsgType.TOAST_MSG:
                    toastMsg(msg.obj.toString());
                    break;
                case MsgType.BATTERY_MSG:
                    arrayList.get(53).setText(msg.obj.toString());
                    break;
                case MsgType.BATTERY_CONN:
                    arrayList.get(50).setText(msg.obj.toString());
                    break;
                case MsgType.DEPTH_SENSOR_MSG:
                    arrayList.get(47).setText(msg.obj.toString());      // 深度传感器反馈
                    break;
                case MsgType.DEPTH_SENSOR_CONN:
                    arrayList.get(44).setText(msg.obj.toString());      // 深度传感器IP
                    break;
                case MsgType.PROPELLER_MSG:
                    arrayList.get(41).setText(msg.obj.toString());      // 推进器反馈
                    break;
                case MsgType.PROPELLER_CONN:
                    arrayList.get(38).setText(msg.obj.toString());      // 推进器IP
                    break;
                case MsgType.LIGHT_MSG:
                    break;
                case MsgType.LIGHT_CONN:
                    break;
                case MsgType.CONTROLLER_MSG:
                    arrayList.get(32).setText(msg.obj.toString());      // 控制反馈
                    break;
                case MsgType.CONTROLLER_CONN:
                    arrayList.get(29).setText(msg.obj.toString());      // 心跳包
                    break;
                case MsgType.RED_CHAO_SHI:
                    chaoshi.setBackgroundResource(R.drawable.chaoshired);
                    break;
                case MsgType.RED_CHAO_SHEN:
                    chaoshen.setBackgroundResource(R.drawable.chaoshenred);
                    break;
                case MsgType.RED_SHA_CHE:
                    shache.setBackgroundResource(R.drawable.zhidongred);
                    break;
                case MsgType.WHITE_NORMAL:
                    chaoshen.setBackgroundResource(R.drawable.chaoshen);
                    chaoshi.setBackgroundResource(R.drawable.chaoshi);
                    shache.setBackgroundResource(R.drawable.zhidong);
                    break;
                case MsgType.RED_HEART:
                    heart_view.setBackgroundResource(R.drawable.heartred);
                    break;
                case MsgType.WHITE_HEART:
                    heart_view.setBackgroundResource(R.drawable.heartwhite);
                    break;
                case MsgType.PROPTESTSEND:
                    arrayList.get(54).setText(msg.obj.toString());          // 测试推进器发送
                    break;
                case MsgType.PROPTESTRECEIVE:
                    arrayList.get(55).setText(msg.obj.toString());          // 测试推进器接收
                    break;
                case MsgType.BATTERYTESTSEND:
                    arrayList.get(57).setText(msg.obj.toString());          // 测试电池发送
                    break;
                case MsgType.BATTERYTESTRECEIVE:
                    arrayList.get(58).setText(msg.obj.toString());          // 测试电池接收
                    break;
                case MsgType.DEPTHTESTSEND:
                    arrayList.get(60).setText(msg.obj.toString());          // 测试深度发送
                    break;
                case MsgType.DEPTHTESTRECEIVE:
                    arrayList.get(61).setText(msg.obj.toString());          // 测试深度接收
                    break;
            }
            super.handleMessage(msg);
        }
    };

    // 从LocationSensor接口反馈显示GPS信息
    public void locationUpdates(Location location)
    {
        if (location != null)
        {
            String longitude = String.valueOf(Constants.keepnumber.format(location.getLongitude()));
            String latitude = String.valueOf(Constants.keepnumber.format(location.getLatitude()));
            String altitude = String.valueOf((int)location.getAltitude());
            String time = Tools.getTime(location.getTime());
            String accuracy = String.valueOf(location.getAccuracy());

            if (arrayList.get(5) != null) {
                arrayList.get(5).setText(longitude);
            }

            if (arrayList.get(8) != null) {
                arrayList.get(8).setText(latitude);
            }

            if (arrayList.get(11) != null) {
                arrayList.get(11).setText(altitude);
            }

            if (arrayList.get(14) != null) {
                arrayList.get(14).setText(time);
            }

            if (arrayList.get(17) != null) {
                arrayList.get(17).setText(accuracy);
            }
        }
    }

    private void toastMsg(final String msg)
    {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void sendMsgToMainThread(int what, Object obj) {
        Message message = mHandler.obtainMessage();
        message.what = what;
        message.obj = obj;
        mHandler.sendMessage(message);
    }

    /**
     * 更新角度信息
     * @param value
     */
    public void updateAttitudeData(float[] value) {
        if (value.length < 3) {
            return;
        }

        if (arrayList.get(20) != null) {
            arrayList.get(20).setText(String.valueOf(value[0]));
        }

        if (arrayList.get(23) != null) {
            arrayList.get(23).setText(String.valueOf(value[1]));
        }

        if (arrayList.get(26) != null) {
            arrayList.get(26).setText(String.valueOf(value[2]));
        }
    }

    public void updateGPScalData(double distanceV, double calculateYawV) {
        distance.setText("距离: " + distanceV);
        calculateYaw.setText("角度: " + calculateYawV);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            // 增加自己的处理逻辑
            System.out.println("I am back !!!!!!!!!!!");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
